<?php

class Core_Component_Catalogue_Business_Goods {

    public function createGoodsDirectory(){
        if(!file_exists(DP_PUB.'catalogue'.DS.'goods'.DS)){
            Soul_Util_FS::makeDirectory(DP_PUB.'catalogue'.DS.'goods'.DS);
        }
        $dir = DP_PUB.'catalogue'.DS.'goods'.DS.date('Ymd').DS;
        Soul_Util_FS::makeDirectory($dir);
        return Soul_Util_FS::makeRandomDirectory($dir);
    }
    
    public function saveGoods(Core_Component_Catalogue_Model_Goods $model){       
        $model->merge()->validate();
        if($model->isNew()){
            $d = $this->createGoodsDirectory();
            $model->setDirectory(str_replace(DP_PUB, '', $d));
        }
        $property = $model->getProperty('images');
        $imgs = array();
        $req = $GLOBALS[RC]->getRequest();
        for($i = 0; $i < $property->getItemCount(); $i++){
            $f = $req->getFile($property->getName().'_'.$i);
            $v = $req->getParameter($property->getPropertyName().'_'.$i, NULL);
            if(!is_null($f)){
                $p = $f->saveRandom(DP_PUB.$model->getDirectory());
                $imgs[] = Soul_Util_Server::pathToUrl($p);
            }elseif(!empty($v)){
                $imgs[] = $v;
            }
        }
        $model->setImages($imgs)->save();
    }
}